package cn.myframe.controller.sys;

import cn.myframe.controller.AbstractController;
import cn.myframe.entity.sys.SysLogEntity;
import cn.myframe.entity.sys.SysParameterEntity;
import cn.myframe.entity.sys.SysShellEntity;
import cn.myframe.log.LogPojo;
import cn.myframe.service.sys.SysLogService;
import cn.myframe.service.sys.SysParameterService;
import cn.myframe.service.sys.SysShellService;
import cn.myframe.utils.AESSecurityUtil;
import cn.myframe.utils.HttpContextUtils;
import cn.myframe.utils.IPUtils;
import cn.myframe.utils.ShiroUtils;
import cn.myframe.utils.annotation.SysLog;
import cn.myframe.utils.core.PageUtils;
import cn.myframe.utils.core.Query;
import cn.myframe.utils.core.R;
import cn.myframe.utils.ssh.SSHData;
import cn.myframe.utils.ssh.SSHMessage;
import cn.myframe.utils.ssh.SSHQueue;
import cn.myframe.utils.ssh.SSHUtils;
import com.alibaba.fastjson.JSON;
import com.jcraft.jsch.ChannelShell;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 远程服务器
 * 
 * @author ynz
 * @email ynz@myframe.cn
 * @date 2017-12-09 21:13:45
 */
@RestController
@RequestMapping("/sys/sysshell")
public class SysShellController  extends AbstractController{
	@Autowired
	private SysShellService sysShellService;
	@Autowired
	private SysParameterService sysParameterService;
	@Autowired
	private SysLogService sysLogService;
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sysshell:list")
	public R list(@RequestParam Map<String, Object> params){
	   // doBefore(params, "sysshell:list");
		//查询列表数据
        Query query = new Query(params);

		List<SysShellEntity> sysShellList = sysShellService.queryList(query);
		
		SysParameterEntity parameter = sysParameterService.queryByKey("adsPort");
		String adsPort = parameter.getParamValue();
		for(SysShellEntity shell : sysShellList){
			if(shell.getType().intValue() == 2){
				boolean result = checkStatus(shell,adsPort);
				//boolean result = false;
				if(result){
					shell.setStatus(2);
				}else{
					shell.setStatus(0);
				}				
			}else{
				shell.setStatus(2);
			}
		}
		int total = sysShellService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(sysShellList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 * @throws Exception 
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sysshell:info")
	public R info(@PathVariable("id") Long id) throws Exception{
		SysShellEntity sysShell = sysShellService.queryObject(id);
		
		changePwd(sysShell);
		return R.ok().put("sysShell", sysShell);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sysshell:save")
	@SysLog("logSaveData")
	public R save(@RequestBody SysShellEntity sysShell){
		sysShellService.save(sysShell);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 * @throws Exception 
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sysshell:update")
	@SysLog("logUpateStatus")
	public R updateShell(@RequestBody SysShellEntity sysShell) throws Exception{
		String password = sysShell.getPassword();
		if(StringUtils.isNotEmpty(password)){
			String key = "myframe.cn";
			password = AESSecurityUtil.encrypt(password, key);
			sysShell.setPassword(password);
		}
		SysShellEntity queryObject = sysShellService.queryObject(sysShell.getId());
		String oldValue = JSON.toJSONStringWithDateFormat(queryObject, JSON.DEFFAULT_DATE_FORMAT);
		
		sysShellService.update(sysShell);
		String returnReslut = JSON.toJSONStringWithDateFormat(sysShell, JSON.DEFFAULT_DATE_FORMAT);
		
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		LogPojo logPojo = new LogPojo();
		logPojo.setIp(IPUtils.getIpAddr(request));
		logPojo.setType(2);
		logPojo.setOperation("updateShell");
		logPojo.setMethod("cn.myframe.controller.sys.SysShellController.updateShell()");
		logPojo.setClassName("SysShellController");
		logPojo.setOperateValue(returnReslut);
		logPojo.setUpdateOld(oldValue);
		SysLogEntity sysLogEntity = new SysLogEntity(logPojo);
		sysLogEntity.setUsername(ShiroUtils.getUserEntity().getUsername());
		sysLogEntity.setCreateBy(ShiroUtils.getUserEntity().getUserId());
		sysLogEntity.setCreateDate(new Date());
		sysLogService.insert(sysLogEntity);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sysshell:delete")
	@SysLog("logDelData")
	public R delete(@RequestBody Long[] ids){
		sysShellService.deleteBatch(ids);
		return R.ok();
	}
	
    /**
     * 检验字段名是否存在重复
     */
    @RequestMapping("/checkExist")
    @ResponseBody
    public String checkExist(String id,String name){
        boolean result = true;
        int count = sysShellService.checkExist(id, name);
        if(count > 0 ){
            result = false;
        }
        return "{\"valid\":" + result + "}";
    }
    
     /**
     * 提交，审核
     */
    @RequestMapping("/audit")
    @SysLog("logAudit")
    public R audit(@RequestBody Long[] ids ,@RequestParam Integer status){      
    	sysShellService.updateStatus(ids , status);
        return R.ok();
    }
    
    @RequestMapping("/send")
    public R send(@RequestBody Map<String,Object> params){      
    	String randomShellId = String.valueOf(params.get("randomShellId"));
    	try{
    		Long id = Long.parseLong(String.valueOf(params.get("id")));
    		
    		//Long id = 1L;
    		String cmd = String.valueOf(params.get("cmd"));
    		//String cmd = "ll";
    		SSHData sshData = SSHUtils.sshMap.get(randomShellId);
        	if(sshData == null){
        		SysShellEntity entity = sysShellService.queryObject(id);
        		changePwd(entity);
        		ChannelShell channelShell = SSHUtils.getShellChannel(entity.getUserName(), entity.getIp(), entity.getPort(), entity.getPassword(),randomShellId);
            	if(channelShell != null){
            		sshData = SSHUtils.sshMap.get(randomShellId);
            	}else{
            		SSHQueue.getInstance().push(new SSHMessage(String.valueOf(randomShellId),"Login server failed,please check the data is right."));
            		return R.error();
            	}
        		
        	}
        	sshData.freshTime();
        	OutputStream outputStream = sshData.getOutputStream();
        	outputStream.write((cmd).getBytes());
        	outputStream.flush();
    	}catch(Exception e){
    		e.printStackTrace();
    		SSHQueue.getInstance().push(new SSHMessage(String.valueOf(randomShellId),"Login server failed,please check the data is right."));
    		return R.error();
    	}
    	
    	
        return R.ok();
    }
    
    /**
     * 转变密码
     * @throws Exception 
     */
	public void changePwd(SysShellEntity entity) throws Exception{
		String password = entity.getPassword();
		if(StringUtils.isNotEmpty(password)){
			String key = "myframe.cn";
			password = AESSecurityUtil.decrypt(password, key);
			entity.setPassword(password);
		}
	}
	
	/**
	 * 刷新时检查系统的状态
	 * @param shell
	 * @return
	 */
	public boolean checkStatus(SysShellEntity shell,String adsPort){
		try {
			if(StringUtils.isNotEmpty(adsPort) && StringUtils.isNotEmpty(shell.getIp())){
				String ip = shell.getIp();
				String url = "http://" + ip + ":" + adsPort + "/getMesage";
			//	String reString = SSLClient.sendGet(url,"",false);
			//	if(StringUtils.isNotEmpty(reString)){
					return true;
			//	}				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@RequestMapping("/getAdsServer")
	public R getAdsServer(){
		List<SysShellEntity> shells = sysShellService.selectAds();
		return R.ok().put("adsList", shells);
	}
}
